﻿using AspNetCoreRateLimit;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using System;
using Zhongjiu.Common;

namespace Zhongjiu.Extensions
{
  /// <summary>
  /// IPLimit限流 启动服务
  /// </summary>
  public static class IpPolicyRateLimitSetup
  {
    public static void AddIpPolicyRateLimitSetup(this IServiceCollection services)
    {
      if (services == null) throw new ArgumentNullException(nameof(services));
      if (Appsettings.app("IpRateLimiting:Enabled").ToBool())
      {
        // needed to store rate limit counters and ip rules
        services.AddMemoryCache();
        //加载ip规则设置
        services.Configure<IpRateLimitOptions>(Appsettings.GetSection("IpRateLimiting"));
        //从appsettings.json中加载客户端规则
        //services.Configure<ClientRateLimitPolicies>(Appsettings.GetSection("ClientRateLimitPolicies"));
        // inject counter and rules stores
        services.AddSingleton<IIpPolicyStore, MemoryCacheIpPolicyStore>();
        services.AddSingleton<IRateLimitCounterStore, MemoryCacheRateLimitCounterStore>();

        // inject counter and rules distributed cache stores
        //分布式部署时，计数器需要使用分布式缓存
        //services.AddSingleton<IIpPolicyStore, DistributedCacheIpPolicyStore>();
        //services.AddSingleton<IRateLimitCounterStore, DistributedCacheRateLimitCounterStore>();

        // the clientId/clientIp resolvers use it.
        services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
        // configuration (resolvers, counter key builders)
        services.AddSingleton<IRateLimitConfiguration, RateLimitConfiguration>();
      }
    }
  }
}